import ajax from 'uni-ajax'
import refreshToken from './refresh'
// import Loading from './loading'
import { APP_BASE_URL, TOKEN_HEADER_NAME } from '@/env.js'
import { cache } from '@/utils/jdk'
// 创建实例
const instance = ajax.create({
  baseURL: APP_BASE_URL,
  loading: '加载中'
})
// const loading = new Loading()

// 添加请求拦截器
instance.interceptors.request.use(config => {
  // loading.show(config.loading)
  // 给每条请求赋值 Token 请求头
  config.header[TOKEN_HEADER_NAME] = cache('token')
  return config
})

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    // loading.hide(response.config.loading)
    // 假设接口返回的 code === 401 时则需要刷新 Token
    if (response.data.code === 401) {
      return refreshToken(() => instance(response.config))
    }
    return response.data
  },
  error => {
    // loading.hide(error.config.loading)
    return Promise.reject(error)
  }
)

export default instance
